package com.biodiv.miracle.web.handler;

import com.biodiv.miracle.ioc.context.ApplicationContext;
import com.biodiv.miracle.web.interceptor.HandlerInterceptor;
import com.biodiv.miracle.web.servlet.DispatcherServlet;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.logging.Logger;

/**
 * @Author: tianquan
 * @CreateTime: 2025-05-26  17:39
 * @Description: 抽象类
 */
public abstract class AbstractHandlerMapping implements HandlerMapping {

    private final Logger logger = Logger.getLogger(AbstractHandlerMapping.class.getName());
    private final Object defaultHandler = "defaultHandler";

    @Override
    public HandlerExecutionChain getHandler(HttpServletRequest request) {
        // controller对应的方法
        Object handler = this.getHandlerInternal(request);
        if (handler == null) {
            handler = defaultHandler;
        }
        if (handler instanceof String handlerStr) {
            ApplicationContext applicationContext = (ApplicationContext) request.getAttribute("applicationContext");
            handler = applicationContext.getBean(handlerStr);
        }

        // 获取当前请求支持的所有拦截器
        DispatcherServlet dispatcherServlet = (DispatcherServlet) request.getAttribute("dispatcherServlet");
        List<HandlerInterceptor> interceptors = dispatcherServlet.getInterceptors(request);

        // todo 后续添加 拦截器 自定义过滤路径功能

        return new HandlerExecutionChain(handler,interceptors);
    }

    protected abstract Object getHandlerInternal(HttpServletRequest request);
}
